package eraserhead.controller;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import eraserhead.boundary.DecisionGUI;
import eraserhead.boundary.DecisionLinesCanvas;
import eraserhead.boundary.WarningWindow;
import eraserhead.entity.Decision;
import eraserhead.entity.Edge;
import eraserhead.xml.request.AddEdgeRequest;


/**
 * Adds the edge to the canvas; assuming user controller permits it to.
 * @author Cian
 * @author Quanquan
 * @author Greg
 * Based upon Cian's A1 Implementation Code.
 */
public class AddEdgeController implements MouseListener {
	
	Decision model;
	
	DecisionLinesCanvas view;

	/**
	 * Create a new {@link AddEdgeController}
	 * @param model {@link Decision} to be associated with this {@link AddEdgeController}
	 * @param view {@link DecisionLinesCanvas} to be associated with this {@link AddEdgeController}
	 */
	public AddEdgeController(Decision model, DecisionLinesCanvas view)
	{
		this.model = model;
		this.view = view;
	}
	
	@Override
	public void mouseClicked(MouseEvent me)
	{
		if (view.getCanAddEdge())
		{
			int lineArraySize = model.getLines().size();
			int width = view.getWidth();
			int spaceBetweenLines = (width - view.margin * 2) / (lineArraySize - 1);
			
			if (me.getY() >= 0 && me.getY() <= view.getHeight()) // need to adjust depending on height of line
			{
				for (int i = 0; i < lineArraySize; i++)
				{		
					if  (i < lineArraySize - 1)
					{
						if (me.getX() >= (view.margin + spaceBetweenLines * i)
								&& me.getX() <= (view.margin + spaceBetweenLines * (i+1)))
							{
								Edge addedEdge = new Edge(i, i + 1 , me.getY());
								
								if (model.addEdge(addedEdge))
								{
									AddEdgeRequest.send(ServerAccessManager.getAccess(), 
											DecisionGUI.getInstance().getModel().getId(), 
											addedEdge);
									view.repaint();
									view.setCanAddEdge(false);
									
									//TODO: set status here.
									return;
								}
								else
								{
									WarningWindow.giveWarning(null, model.getErrorMsg());
								}
						}
					}
				}
			}
		}
	}

	@Override
	public void mousePressed(MouseEvent e) {
	}

	@Override
	public void mouseReleased(MouseEvent e) {	
	}

	@Override
	public void mouseEntered(MouseEvent e) {
	}

	@Override
	public void mouseExited(MouseEvent e) {	
	}	
}
